
//工作空间名称：
var workSpace = "ZJRS"
//坐标系：
var srsName = "EPSG:4326"
//天地图KEY:
var TiandituKey = "1d11420a769aa2d5763e1a67378995bb"
//影像底图图层（天地图）：
var baseImgLayer = "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + TiandituKey
//市级行政区图层名：
var shijiLayer = "ZJRS:District"
//县级行政区图层名：
var xianjiLayer = "ZJRS:County2020"
//结合表图层名：
var targetLayer = "ZJRS:AllJHB"
//属性查询字段名（包括调用影像时匹配的字段名）：
var field = "ImageName"
//属性查询字段值（在该范围内匹配）：
//var valuearr=new Array('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216','GF1_PMS1_E120.1_N30.3_20130825_L1A0000074538-PAN1')
//当前页所有结合表字段值（名称）数组（淡黄色区域显示）：
var lightimgarr = new Array('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216', 'GF1_PMS1_E120.1_N30.3_20130825_L1A0000074538-PAN1')

//平移系数
var panRate = 10; //单次平移时间(毫秒)
var panLength = 6; //单次平移距离系数

var map;
/*关于缩放：若地图自带缩放按钮无法使用，可新建相关按钮，
调用zoomMinus()及zoomPlus()即可缩小/放大，
参数不填默认为1（即缩/放1级）*/


//选中行政区边界样式(红色轮廓高亮)
var boundSource = new ol.source.Vector();
var boundVector = new ol.layer.Vector({
    source: boundSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(255, 0, 0, 1.0)',
            width: 5
        })
    }),
    zIndex: 994
});

//结果样式(黄色半透明显示)
var resultSource = new ol.source.Vector();
var resultVector = new ol.layer.Vector({
    title: "结合表",
    source: resultSource,
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(254, 209, 16, 1.0)'
        })
    }),
    zIndex: 996
});

//高亮选中结合表结果样式
var spaceSource = new ol.source.Vector();
var spaceVector = new ol.layer.Vector({
    source: spaceSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(255, 0, 0, 1.0)',
            width: 3
        })
    }),
    zIndex: 999
});

//当前页结合表样式(蓝色边框显示)
var cpageSource = new ol.source.Vector();
var cpageVector = new ol.layer.Vector({
    source: cpageSource,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 255, 1.0)',
            width: 2
        })
    }),
    zIndex: 995
});

//图形绘制样式
var drawSource = new ol.source.Vector({wrapX: false});
var drawVector = new ol.layer.Vector({
    source: drawSource,
    style: new ol.style.Style({
        fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)'
        }),
        stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 2
        }),
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
                color: '#ffcc33'
            })
        })
    }),
    zIndex: 997
});

var extent = [118.02826723613758, 27.144488188499174, 122.82884918112711, 31.18275392885731];
//var extent = [114.7669, 24.8236, 126.0337, 33.4935];
//投影坐标系
var projection = new ol.proj.Projection({code: srsName, units: ol.proj.Units, extent: extent});
//中心点
var center = ol.extent.getCenter(extent);

//实例化鼠标位置控件（MousePosition）
var mousePositionControl = new ol.control.MousePosition({
    //坐标格式
    coordinateFormat: ol.coordinate.createStringXY(6),
    //地图投影坐标系（若未设置则输出为默认投影坐标系下的坐标）
    //projection: 'EPSG:4326',
    //坐标信息显示样式类名，默认是'ol-mouse-position'
    className: 'custom-mouse-position',
    //显示鼠标位置信息的目标容器
    target: document.getElementById('mouse-position'),
    //未定义坐标的标记
    undefinedHTML: '&nbsp;'
});


function init() {
    //创建一个地图容器
    map = new ol.Map({
        target: 'map',
        view: new ol.View({
            center: center,
            zoom: 1.3,
            projection: projection,
            extent: extent,
            minZoom: 1.3,
            //zoomFactor: Math.pow(5,1/5)
        }),
        interactions: new ol.interaction.defaults({
            doubleClickZoom: false
        }),
        controls: ol.control.defaults({//地图中默认控件
            /* @type {ol.control.Attribution} */
            attributionOptions: ({
                //地图数据源信息控件是否可收缩,默认为true
                collapsible: true
            })
        }).extend([mousePositionControl])//加载鼠标位置控件
    });

    /*======创建基于地图文档的WMS图层对象并加载到地图中======*/
    TiandiMap_img = new ol.layer.Tile({
        title: "天地图影像图",
        source: new ol.source.XYZ({
            url: baseImgLayer,
            wrapX: false,
            crossOrigin: 'anonymous'
        })
    });
    //基于地图文档的WMS访问基地址
    wmsUrl = workSpaceUrl + "/wms";
    //创建基于地图文档的WMS图层对象
    wmsVectLayer0 = new ol.layer.Image({
        title: "市级行政区划图",
        source: new ol.source.ImageWMS({
            //WMS服务地址
            url: wmsUrl,
            //图层等参数，若WMS版本较老必须加上版本号
            params: {'LAYERS': shijiLayer, 'VERSION': '1.1.1', 'TILED': true},
            projection: projection,
            //服务类型
            serverType: 'geoserver',
            crossOrigin: 'anonymous'
        })

    });
    wmsVectLayer1 = new ol.layer.Image({
        title: "县级行政区划图",
        source: new ol.source.ImageWMS({
            //WMS服务地址
            url: wmsUrl,
            //图层等参数，若WMS版本较老必须加上版本号
            params: {'LAYERS': xianjiLayer, 'VERSION': '1.1.1', 'TILED': true},
            projection: projection,
            //服务类型
            serverType: 'geoserver',
            crossOrigin: 'anonymous'
        })

    });
    map.addLayer(TiandiMap_img);
    map.addLayer(wmsVectLayer0);
    map.addLayer(wmsVectLayer1);

}

init();
map.addLayer(drawVector);
map.addLayer(spaceVector);
map.addLayer(cpageVector);
//加载图层
layui.use(['laydate', 'slider', 'upload', 'table', 'soulTable', 'jquery', 'tree', 'util'], function () {
    const tree = layui.tree;
    var data2 = [{
        title: '图层切换',
        children: [
            /*{title: "天地图影像图", checked: true, spread: true,id: "layer1"},
            {title: "市级行政区划图", checked: true, spread: true,id: "layer2"},
            {title: "县级行政区划图", checked: true, spread: true,id: "layer3"}*/
            /*{
                title: '天地图影像图',

                checked: true
            },
            {
                title: '市级行政区划图',
                id: "layer2",
                checked: true
            },
            {
                title: '县级行政区划图',
                id: "layer3",
                checked: true,
            }*/
        ]
    }]
    let layers = map.getLayers().array_;
    for (var layerOne in layers) {
        if (JSON.stringify(layers[layerOne].get("title")) !== undefined) {
            data2[0]["children"].push({
                title: layers[layerOne].get("title"),
                checked: true,
                spread: true,
                id: "layer" + layerOne
            });
        }
    }
    console.log("数据" + data2[0]["children"][0]["checked"]);
    tree.render({
        elem: '#demo-tree2',
        data: data2,
        showCheckbox: true,
        checked: true,
        oncheck: function (obj) {
            console.log(obj.data); //得到当前点击的节点数据
            console.log(obj.checked); //得到当前节点的展开状态：open、close、normal
            console.log(obj.elem); //得到当前节点元素

            if (obj.data["title"] === "图层切换") {
                if (obj.checked === false) {
                    let layers = map.getLayers().array_;
                    for (var layerOne in layers) {
                        if (JSON.stringify(layers[layerOne].get("title")) !== undefined) {
                            layers[layerOne].setVisible(false);
                        }
                    }
                } else {
                    for (var layerOne in layers) {
                        if (JSON.stringify(layers[layerOne].get("title")) !== undefined) {
                            layers[layerOne].setVisible(true);
                        }
                    }

                }
            } else {
                for (var layerOne in layers) {
                    if (layers[layerOne].get("title") === obj.data["title"]) {
                        layers[layerOne].setVisible(obj.checked);
                        break;
                    }
                }

            }
			}
        });
});

//地图视图的初始参数
var view = map.getView();
//var zoom = view.getZoom();
//var center = view.getCenter();
//var rotation = view.getRotation();

//鹰眼底图
var wmsVectLayer3 = new ol.layer.Image({
    source: new ol.source.ImageWMS({
        //WMS服务地址
        url: wmsUrl,
        //图层等参数，若WMS版本较老必须加上版本号
        params: {'LAYERS': shijiLayer + ',' + xianjiLayer, 'VERSION': '1.1.1', 'TILED': true},
        projection: projection,
        //服务类型
        serverType: 'geoserver'
    })
});

//鹰眼地图控件
var extent1 = [112, 23, 128, 37]
var overviewMapControl = new ol.control.OverviewMap({
    //鹰眼控件样式（see in overviewmap-custom.html to see the custom CSS used）
    className: 'ol-overviewmap ol-custom-overviewmap',
    //鹰眼中加载同坐标系下不同数据源的图层
    layers: [wmsVectLayer3],
    //鹰眼控件展开时功能按钮上的标识（网页的JS的字符编码）
    collapseLabel: '\u00BB',
    //鹰眼控件折叠时功能按钮上的标识（网页的JS的字符编码）
    label: '\u00AB',
    //初始为展开显示方式
    collapsed: false,
    //maxResolution:this.map.maxResolution/4,
    view: new ol.View({
        center: center,
        zoom: 1,
        projection: new ol.proj.Projection({code: srsName, units: ol.proj.Units, extent: extent1}),
        extent: extent1
    }),
});
map.addControl(overviewMapControl);


// 添加图层切换控件
/*var layerSwitcher = new ol.control.LayerSwitcher({
	tipLabel: '切换图层'
});
map.addControl(layerSwitcher);*/


//显示全图
function reSetView() {
    //初始中心点
    view.setCenter(center);
    //初始旋转角度
    view.setRotation(0);
    //初始缩放级数
    view.setZoom(1.3);
}

function zoomMinus(val = 1) {
    //获取地图视图
    var view1 = map.getView();
    //获得当前缩放级数
    var zoom1 = view.getZoom();
    //地图缩小一级
    if (zoom1 > 1) {
        view1.setZoom(zoom1 - val);
    }
}

function zoomPlus(val = 1) {
    //获取地图视图
    var view2 = map.getView();
    //获得当前缩放级数
    var zoom2 = view.getZoom();
    //地图放大一级
    if (zoom2 < 28) {
        view1.setZoom(zoom2 + val);
    }
}

//绘制几何图形
var feature;
var draw;
var typeSelect = document.getElementById('type');
var value;

function addInteraction() {
    if (drawSource == null) {
        drawSource = new ol.source.Vector({wrapX: false});
        //添加绘制层数据源
        drawVector.setSource(drawSource);
    }
    if (value === 'Polygon') {
        draw = new ol.interaction.Draw({
            source: drawSource,
            type: 'Polygon'
        });
    } else if (value === 'Box') {
        draw = new ol.interaction.Draw({
            source: drawSource,
            type: 'Circle',
            geometryFunction: ol.interaction.Draw.createBox()
        });
    } else if (value === 'Square') {
        draw = new ol.interaction.Draw({
            source: drawSource,
            type: 'Circle',
            geometryFunction: ol.interaction.Draw.createRegularPolygon(4)
        });
    } else if (value === 'LineString') {
        draw = new ol.interaction.Draw({
            source: drawSource,
            type: 'LineString'
        });
    } else if (value === 'Point') {
        draw = new ol.interaction.Draw({
            source: drawSource,
            type: 'Point'
        });
    } else {
        draw = new ol.interaction.Draw({
            source: drawSource,
            type: 'Polygon'
        });
    }
    map.addInteraction(draw);
    draw.on('drawend', function (evt) {
        feature = evt.feature;
        map.removeInteraction(draw);
        map.getView().fit(feature.getGeometry().getExtent());
        zoomMinus(0.5);
    })

}

//选择绘制类型事件
function DrawRec(val) {
    ClearDraw();
    if (val == 1) {
        value = "Polygon";
    } else {
        value = "Box";
    }
    map.removeInteraction(draw);
    addInteraction();
};

//加载选中的行政区边界
var hasBo = 0 //边界展示状态
var Boundary;

function loadBoundary(level, name) {
    ClearDraw();
    if (level != 0) {
        if (level == 1) {//加载市级行政区边界
            var RequestBound = new ol.format.WFS().writeGetFeature({
                srsName: srsName,
                featureNS: workSpaceUrl,
                featurePrefix: workSpace,
                featureTypes: [shijiLayer],
                outputFormat: 'application/json',
                filter:
                    ol.format.filter.equalTo('NAME', name),
            });
        } else {//加载县级行政区边界
            var RequestBound = new ol.format.WFS().writeGetFeature({
                srsName: srsName,
                featureNS: workSpaceUrl,
                featurePrefix: workSpace,
                featureTypes: [xianjiLayer],
                outputFormat: 'application/json',
                filter:
                    ol.format.filter.equalTo('NAME', name),
            });
        }
        fetch(workSpaceUrl + '/wfs', {
            method: 'POST',
            body: new XMLSerializer().serializeToString(RequestBound)
        }).then(function (response) {
            return response.json();
        }).then(function (json) {
            Boundary = new ol.format.GeoJSON().readFeatures(json);
            if (Boundary.length == 0) {
                layer.msg('未找到相关行政区')
            } else {
                boundSource = new ol.source.Vector();
                boundSource.addFeatures(Boundary);
                boundVector.setSource(boundSource);
                map.getView().fit(boundSource.getExtent());
            }
        });
        map.addLayer(boundVector);
        hasBo = 1
    }
}


//读取上传文件
function upload(input) {
    console.log("开始导入csv")
    ClearDraw();
    //定义坐标范围数组
    let csvPointsArr = new Array;

    let csvfile = input.files[0];	//取到当前上传的文件
    fileType = csvfile.name.split('.');	//取到文件名并使用“.”进行切割
    if (fileType[fileType.length - 1] != 'csv' && fileType[fileType.length - 1] != 'txt') {	//判断文件类型
        alert('文件类型错误！');
        //document.getElementById('file').value = '';
        return
    }
    let reader = new FileReader();	//new一个FileReader对象实例
    reader.readAsText(csvfile);	//读取csv文件
    reader.onload = () => {		//读取成功完成后触发事件
        let fileData = reader.result	//获取读取的数据
        if (fileData == "") {
            alert("ERROR:文件内容为空")
            //document.getElementById('file').value = '';
            return
        }

        //获取坐标并格式化
        let coor = fileData.split(';')
        //let coor=fileData.split('"')[1].split(';')
        for (let i in coor) {
            let m = coor[i].split().toString()
            csvPointsArr.push(m.split(','))
        }
        for (let i in csvPointsArr) {
            let flt = eval(csvPointsArr[i][0])
            csvPointsArr[i][0] = eval(csvPointsArr[i][1])
            csvPointsArr[i][1] = flt
        }
        csvPointsArr.push(csvPointsArr[0])
        console.log("csv读取成功")
        DrawCSVPol(csvPointsArr)
    }
}

//输入经纬度绘制矩形
var XYRec=false //是否已存在矩形
function DrawXYRec(){
    let nwX=$('#lefttopX').val()
    let nwY=$('#lefttopY').val()
    let seX=$('#rightBotX').val()
    let seY=$('#rightBotY').val()
    if(nwX==""||nwY==""||seX==""||seY==""){
        layer.msg("请输入完整坐标")
        return
    }
    ClearDraw();
    let coordArr=[[Math.min(nwX,seX),Math.max(nwY,seY)],[Math.min(nwX,seX),Math.min(nwY,seY)],[Math.max(nwX,seX),Math.min(nwY,seY)],[Math.max(nwX,seX),Math.max(nwY,seY)]]
    console.log(coordArr)
    DrawCSVPol(coordArr);
    XYRec=true
}
//清除输入的经纬度及矩形
function clearXYRec(){
    $('#lefttopX').val('')
    $('#lefttopY').val('')
    $('#rightBotX').val('')
    $('#rightBotY').val('')
    if(XYRec){
        ClearDraw();
        XYRec=false
    }
}

//根据坐标绘制多边形
var csvPolygon;
function DrawCSVPol(arr) {
    csvPolygon = new ol.Feature({
        geometry: new ol.geom.Polygon([arr])
    });

    drawSource = new ol.source.Vector({
        features: [csvPolygon]
    });
    drawVector.setSource(drawSource);
    map.getView().fit(drawSource.getExtent());
}

//读取shp文件
var shpfeatures;
function uploadshp(input){
    ClearDraw();
    let parser = new ol.format.GeoJSON()
    let shpfile = input.files[0];	//取到当前上传的文件
    fileType = shpfile.name.split('.');	//取到文件名并使用“.”进行切割
    if(fileType[fileType.length - 1] != 'shp') {	//判断文件类型
        alert('文件类型错误！');
        //document.getElementById('file1').value = '';
        return
    }
    if (shpfile) {
        let opts = { shp: shpfile };
        shapefile = new Shapefile(opts, function(data){
            shpfeatures = parser.readFeatures(data.geojson);
            drawSource = new ol.source.Vector({
                features: [shpfeatures[0]]
            });
            drawVector.setSource(drawSource);
            map.getView().fit(drawSource.getExtent());
        });
    }
}


//获取空间范围
function getSpatialExtent(){
    let spatialExtentArr;
    if(feature!==null&&feature!==undefined){
        spatialExtentArr=feature.getGeometry().getCoordinates();
    }
    else if(csvPolygon!==null&&csvPolygon!==undefined){
        spatialExtentArr=csvPolygon.getGeometry().getCoordinates();
    }
    else if(shpfeatures!==null&&shpfeatures!==undefined){
        spatialExtentArr=shpfeatures[0].getGeometry().getCoordinates();
    }
    else if(Boundary!==null&&Boundary!==undefined){
        spatialExtentArr=Boundary[0].getGeometry().getCoordinates();
        spatialExtentArr=spatialExtentArr[0]
    }
    else{
        alert("未选定任何空间区域")
        return false;
    }
    for(let i in spatialExtentArr[0]){
        spatialExtentArr[0][i]=spatialExtentArr[0][i].join(" ");
    }
    spatialExtentArr[0]=spatialExtentArr[0].join(",");
    console.log("获取坐标范围："+spatialExtentArr[0])
    return spatialExtentArr[0]
}


//查询
var q = 0//判断是否查询过
function query(valuearr, way) {

    //清空上一次查询结果
    var resultArray = ""
    resultArray = new Array();
    resultSource = null;
    resultVector.setSource(resultSource);

    //读取影像名数组
    var nameFilterArr = new Array();
    for (let i in valuearr) {
        nameFilterArr.push("ol.format.filter.equalTo('" + field + "','" + valuearr[i] + "')")
    }

    //根据查询方法确定空间条件
    if (way == 1 && Boundary !== null && Boundary !== undefined) {
        var geomPol = "Boundary[0].getGeometry()"
    } else if (way == 2 && feature !== null && feature !== undefined) {
        var geomPol = "feature.getGeometry()"
    } else if (way == 3 && csvPolygon !== null && csvPolygon !== undefined) {
        var geomPol = "csvPolygon.getGeometry()"
    } else if (way == 4 && shpfeatures !== null && shpfeatures !== undefined) {
        var geomPol = "shpfeatures[0].getGeometry()"
    } else {
        alert("未选定任何查询区域")
        return false;
    }

    //初始化过滤条件
    if (valuearr.length > 1) {
        var filters = "ol.format.filter.and(" +
            "ol.format.filter.or(" + nameFilterArr.toString() + ")," +
            "ol.format.filter.intersects('the_geom', " + geomPol + ")" +
            ")";
    } else if (valuearr.length == 1) {
        var filters = "ol.format.filter.and(" +
            nameFilterArr.toString() + "," +
            "ol.format.filter.intersects('the_geom', " + geomPol + ")" +
            ")";
    } else {
        var filters = "ol.format.filter.intersects('the_geom', " + geomPol + ")";
        alert("未选择影像属性，仅进行空间查询")
    }

    //定义查询请求
    var resultRequest = new ol.format.WFS().writeGetFeature({
        srsName: srsName,
        featureNS: workSpaceUrl,
        featurePrefix: workSpace,
        featureTypes: [targetLayer],
        outputFormat: 'application/json',
        filter: eval(filters)
    });
    layer.msg("开始查询", {
        icon: 5,
        time: 1000
    });

    fetch(workSpaceUrl + '/wfs', {
        method: 'POST',
        body: new XMLSerializer().serializeToString(resultRequest)
    }).then(function (response) {
        return response.json();
    }).then(function (json) {
        var features = new ol.format.GeoJSON().readFeatures(json);
        for (let i in features) {
            resultArray.push(features[i]["values_"][field])
        }
        if (features.length == 0) {
            layer.msg("没有符合条件的数据", {
                icon: 5,
                time: 1000
            });

        } else {
            layer.msg("\"查询到\" + features.length + \"记录\"", {
                icon: 5,
                time: 1000
            });

            resultSource = new ol.source.Vector();
            resultSource.addFeatures(features);
            resultVector.setSource(resultSource);
            map.getView().fit(resultSource.getExtent());
        }
    });
    layer.msg("查询结束");
    q = 1;
    resultVector.setOpacity(0.35);
    map.addLayer(resultVector);
    return resultArray;
}

//清除按钮
function ClearDraw() {
    //清空上传的文件
    /*if(document.getElementById('file').value != ''){
        document.getElementById('file').value = '';
    }
    if(document.getElementById('file1').value != ''){
        document.getElementById('file1').value = '';
    }*/
    //清空绘制图形
    value = ""
    drawSource = null;
    drawVector.setSource(drawSource);
    map.removeInteraction(draw);
    if (feature !== null) {
        feature = null;
    }
    //清除查询结果
    if (spaceSource !== null) {
        spaceSource = null;
        spaceVector.setSource(spaceSource);
    }
    if (q == 1) {//如果查询过，就删除图层
        map.removeLayer(resultVector);
        q = 0
        resultArray = ""
    }
    if (hasBo == 1) {//如果加载过，就删除边界
        Boundary = null
        boundSource = null;
        boundVector.setSource(boundSource);
        map.removeLayer(boundVector);
        hasBo = 0
    }
    if (display == 1) {//如果正在显示，就删除图层
        map.removeLayer(displayImgLayer);
        display = 0
    }
    //清除高亮
    spaceSource = null;
    spaceVector.setSource(spaceSource);
    cpageSource = null;
    cpageVector.setSource(cpageSource);
}


//高亮选中结合表边框
function Highlight(imgname) {
    spaceSource = null;
    spaceVector.setSource(spaceSource);
    var featureRequest2 = new ol.format.WFS().writeGetFeature({
        srsName: srsName,
        featureNS: workSpaceUrl,
        featurePrefix: workSpace,
        featureTypes: [targetLayer],
        outputFormat: 'application/json',
        filter:
            ol.format.filter.equalTo(field, imgname),
    });

    fetch(workSpaceUrl + '/wfs', {
        method: 'POST',
        body: new XMLSerializer().serializeToString(featureRequest2)
    }).then(function (response) {
        return response.json();
    }).then(function (json) {
        var features = new ol.format.GeoJSON().readFeatures(json);
        if (features.length == 0) {
            console.log('地图上找不到该数据')
        } else {
            spaceSource = new ol.source.Vector();
            spaceSource.addFeatures(features);
            spaceVector.setSource(spaceSource);
            //map.getView().fit(spaceSource.getExtent());
        }
    });
}

//清除红色高亮框
function clearLight() {
    spaceSource = null;
    spaceVector.setSource(spaceSource);
}

//滑动高亮按钮
/*
var highlightBtn1 = document.getElementById("#highlightBtn1");
highlightBtn.onmouseover = function (e) {
	Highlight('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216');
}
highlightBtn1.onmouseout = function (e) {
	clearLight(); //鼠标移出清除高亮
}
*/

//点亮当前页结合表区域（蓝色边框）
function light(lightimgarr) {
    cpageSource = null;
    cpageVector.setSource(cpageSource);
    cpageSource = new ol.source.Vector();
    for (let i in lightimgarr) {
        lightRequest(lightimgarr[i]);
    }
}
function lightRequest(imgname) {
    var featureRequest1 = new ol.format.WFS().writeGetFeature({
        srsName: srsName,
        featureNS: workSpaceUrl,
        featurePrefix: workSpace,
        featureTypes: [targetLayer],
        outputFormat: 'application/json',
        filter:
            ol.format.filter.equalTo(field, imgname),
    });

    fetch(workSpaceUrl + '/wfs', {
        method: 'POST',
        body: new XMLSerializer().serializeToString(featureRequest1)
    }).then(function (response) {
        return response.json();
    }).then(function (json) {
        var features = new ol.format.GeoJSON().readFeatures(json);
        cpageSource.addFeatures(features);
        cpageVector.setSource(cpageSource);
    });

}

//显示当前页结合表按钮
/*
var upbtn = document.getElementById("lightBtn");
upbtn.onclick = function (e) {
	light(lightimgarr);
}
*/

//显示单个具体影像
var display = 0//影像展示状态
var displayImgLayer;

function displayImg(imgname) {
    undisplayImg();
    let imgformat;
    if(imgname.substr(imgname.lastIndexOf('_') + 1)=="P"){
        imgformat="image/png";//对单波段影像采用PNG格式调用
        console.log("map.js: display as PNG")
    }else{
        imgformat="image/gif";
        console.log("map.js: display as GIF")
    }
    displayImgLayer = new ol.layer.Image({
        title: imgname,
        source: new ol.source.ImageWMS({
            //WMS服务地址
            url: wmsUrl,
            //图层等参数，若WMS版本较老必须加上版本号
            params: {'LAYERS': workSpace + ':' + imgname, 'VERSION': '1.1.1', 'FORMAT': imgformat},
            projection: projection,
            //服务类型
            serverType: 'geoserver',
            crossOrigin: 'anonymous'
        }),
        zIndex: 998
    });
    displayImgLayer.setOpacity(1000)
    map.addLayer(displayImgLayer);
    display = 1;
}

//移除单个具体影像
function undisplayImg() {
    if (display == 1) {
        map.removeLayer(displayImgLayer);
        display = 0
    }
}

//截图
function toImg() {
    map.once('postcompose', function (event) {
        var canvas = event.context.canvas
        canvas.toBlob(function (blob) {
            saveAs(blob, 'map_output.png')
        })
    })
    map.renderSync()
}

//地图平移
function panDirection(direction) {
    var lonlat = 0.00000000001 * panLength;//平移系数
    var mapCenter = view.getCenter();
    switch (direction) {
        case 'north':
            mapCenter[1] += lonlat * Math.pow(2, 30 - view.getZoom());
            break;
        case "south":
            mapCenter[1] -= lonlat * Math.pow(2, 30 - view.getZoom());
            break;
        case "west":
            mapCenter[0] -= lonlat * Math.pow(2, 30 - view.getZoom());
            break;
        case "east":
            mapCenter[0] += lonlat * Math.pow(2, 30 - view.getZoom());
            break;
    }
    //更改center 实现地图平移
    view.animate({
        center: mapCenter,
    });
    //对地图进行渲染
    //map.render();
}

/*var tid;
var upbtn = document.getElementById("moveUp");

upbtn.onmousedown = function (e) {
	tid = setInterval(function () {
		panDirection("north");
	}, panRate);
}

upbtn.onmouseup = function (e) {
	clearInterval(tid);
}

upbtn.onmouseout = function (e) {
	clearInterval(tid);
}

var downbtn = document.getElementById("moveDown");

downbtn.onmousedown = function (e) {
	tid = setInterval(function () {
		panDirection("south");
	}, panRate);
}

downbtn.onmouseup = function (e) {
	clearInterval(tid);
}

downbtn.onmouseout = function (e) {
	clearInterval(tid);
}

var leftbtn = document.getElementById("moveLeft");
leftbtn.onmousedown = function (e) {
	tid = setInterval(function () {
		panDirection("west");
	}, panRate);
}

leftbtn.onmouseup = function (e) {
	clearInterval(tid);
}

leftbtn.onmouseout = function (e) {
	clearInterval(tid);
}

var rightbtn = document.getElementById("moveRight");

rightbtn.onmousedown = function (e) {
	tid = setInterval(function () {
		panDirection("east");
	}, panRate);
}
rightbtn.onmouseup = function (e) {
	clearInterval(tid);
}
rightbtn.onmouseout = function (e) {
	clearInterval(tid);
}*/

//监听图层切换按钮的点击
